package cn.edu.hstc.wm.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.message.BasicNameValuePair;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import cn.edu.hstc.wm.AppConfigs;
import cn.edu.hstc.wm.bean.Category;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.utils.LogUtil;

/**
 * 店铺服务提供程序
 */
public class StoreService {

	/**
	 * WebService 命名空间
	 */
	public static final String SERVICE_NS = AppConfigs.SERVICE_NS;

	/**
	 * 提供WebService服务的地址
	 */
	public static final String SERVICE_URL = AppConfigs.WEB_SERVICE_URL;

	/**
	 * 根据传入的请求 和参数获取数据
	 * 
	 * @param soapAction
	 * @param param
	 * @return
	 */
	public static List<Store> getStoresListByMethod(String soapAction, List<BasicNameValuePair> param) {
		// 创建HttpTransportSE 传输对象
		final HttpTransportSE httpTransportSE = new HttpTransportSE(SERVICE_URL, AppConfigs.HTTP_TIMEOUT);
		// 开启调试
		httpTransportSE.debug = true;

		// 使用SOAP1.1协议创建Envelope对象 ,ver12版本
		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);

		// 实例化SoapObject对象
		SoapObject soapObject = new SoapObject(SERVICE_NS, soapAction);

		// 如果有参数就添加参数
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				soapObject.addProperty(param.get(i).getName(), param.get(i).getValue());
			}
		}

		//
		// envelope.setOutputSoapObject(soapObject);
		envelope.bodyOut = soapObject;

		// 设置与.net提供的web service保持较好的兼容性
		// envelope.dotNet = true;

		// 调用web service ,如果异常则直接返回空
		try {
			httpTransportSE.call(null, envelope);
		} catch (HttpResponseException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (XmlPullParserException e) {
			e.printStackTrace();
			return null;
		}

		// 有响应且获取内容不为空
		try {
			if (envelope.getResponse() != null) {
				// 获取服务器响应返回的soap消息
				// SoapObject detail = (SoapObject) envelope.getResponse();
				SoapObject resultObject = (SoapObject) envelope.bodyIn;

				// Log.d("resultObject", resultObject.toString());
				return parseData(resultObject);
				// return null;
			}
		} catch (SoapFault e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	/**
	 * 根据传入的请求 和参数获取数据 使用异步线程,导致数据一直在获取的状态,
	 * 
	 * @param soapAction
	 * @param param
	 * @return
	 */
	private static List<Store> getStoresByMethod(String soapAction, List<BasicNameValuePair> param) {

		// 创建HttpTransportSE 传输对象 ,超时时间5s
		final HttpTransportSE httpTransportSE = new HttpTransportSE(SERVICE_URL, AppConfigs.HTTP_TIMEOUT);

		// 开启调试
		httpTransportSE.debug = true;

		// 使用SOAP1.1协议创建Envelope对象 ,ver12版本
		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);

		// 实例化SoapObject对象
		SoapObject soapObject = new SoapObject(SERVICE_NS, soapAction);

		// 如果有参数就添加参数
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				soapObject.addProperty(param.get(i).getName(), param.get(i).getValue());
			}
		}

		//
		// envelope.setOutputSoapObject(soapObject);
		envelope.bodyOut = soapObject;

		// 设置与.net提供的web service保持较好的兼容性
		// envelope.dotNet = true;

		// 使用异步计算,回调方法返回获取的内容
		FutureTask<List<Store>> task = new FutureTask<List<Store>>(new Callable<List<Store>>() {

			@Override
			public List<Store> call() throws Exception {
				// 调用web service
				httpTransportSE.call(null, envelope);

				// 有响应且获取内容不为空
				if (envelope.getResponse() != null) {
					// 获取服务器响应返回的soap消息
					// SoapObject detail = (SoapObject) envelope.getResponse();
					SoapObject resultObject = (SoapObject) envelope.bodyIn;

					return parseData(resultObject);

				}
				return null;
			}
		});

		new Thread(task).start();

		try {
			// 等待获取到后返回内容
			return task.get();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从soapObject 消息中获取到数据,解析数据并生成集合对象返回
	 * 
	 * @param resultObject
	 * @return
	 */
	private static List<Store> parseData(SoapObject resultObject) {
		// 解析服务器响应的soap消息
		List<Store> list = new ArrayList<Store>();
		for (int i = 0; i < resultObject.getPropertyCount(); i++) {
			SoapObject childObject = (SoapObject) resultObject.getProperty(i);
			Store store = new Store();
			// Log.d("childObject", i + "  " + childObject.toString());

			// 解析评论
			// SoapObject commentObject = (SoapObject)
			// childObject.getProperty(1);
			// List<Comment> comments = new ArrayList<Comment>();
			// for (int j = 0; j < commentObject.getPropertyCount(); j++) {
			// Comment comment = new Comment();
			// comment.setComment(commentObject.getPropertyAsString(0));
			// comment.setId((Integer) commentObject.getProperty(1));
			// comment.setScore((Double) commentObject.getProperty(2));
			// comments.add(comment);
			// }
			// store.setComments(comments);

			store.setAddress(childObject.getPropertyAsString("address"));
			store.setGroup(Integer.parseInt(childObject.getPropertyAsString("group")));
			store.setId(Integer.parseInt(childObject.getPropertyAsString("id")));
			store.setImageName(childObject.getPropertyAsString("imageName"));
			store.setIntrodution(childObject.getPropertyAsString("introdution"));
			store.setLong_number(childObject.getPropertyAsString("long_number"));
			store.setName(childObject.getPropertyAsString("name"));
			store.setScore(Double.parseDouble(childObject.getPropertyAsString("score")));
			store.setSend_price(Integer.parseInt(childObject.getPropertyAsString("send_price")));
			store.setShop_time(childObject.getPropertyAsString("shop_time"));
			store.setShort_number(childObject.getPropertyAsString("short_number"));
			store.setSpeed(Integer.parseInt(childObject.getPropertyAsString("speed")));
			store.setStart_price(Integer.parseInt(childObject.getPropertyAsString("start_price")));
			store.setSuport_SMS(Integer.parseInt(childObject.getPropertyAsString("suport_SMS")));
			store.setSuport_call(Integer.parseInt(childObject.getPropertyAsString("suport_call")));
			store.setSuport_order(Integer.parseInt(childObject.getPropertyAsString("suport_order")));
			store.setSuport_send(Integer.parseInt(childObject.getPropertyAsString("suport_send")));
			// store.setCategory(childObject.getProperty(""));
			list.add(store);
		}
		return list;
	}

	/**
	 * 获取所有店铺的个数
	 * 
	 * @return
	 */
	public static int getStoresCount() throws Exception {
		String soapAction = "getStoresCount";
		SoapObject resultObject = SoapService.getSoapObject(soapAction, null);

		// return
		// Integer.parseInt(resultObject.getPropertyAsString("getStoresCount"));
		return Integer.parseInt(resultObject.getProperty(0).toString());
	}

	/**
	 * 获取所有的店铺
	 * 
	 * @return 所有的店铺
	 * @throws Exception
	 */
	public static List<Store> getAllStores() throws Exception {
		String methodAction = "getAllStores";
		return getStoresByMethod(methodAction, null);
	}

	/**
	 * 根据分类id来获取所有的店铺
	 * 
	 * @param id
	 *            指定分类的id
	 * @return 指定分类的所有店铺
	 * @throws Exception
	 */
	public static List<Store> getStoresById(int id) throws Exception {
		String methodAction = "getStoresById";
		List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
		param.add(new BasicNameValuePair("id", id + ""));
		// return getStoresByMethod(methodAction, param);
		return getStoresListByMethod(methodAction, param);

	}

	/**
	 * 查找所有分类
	 * 
	 * @return
	 * @throws Exception
	 */
	public static List<Category> getCategories() throws Exception {
		String soapAction = "getCategories";
		// 返回分类结果
		SoapObject resultObject = (SoapObject) SoapService.getSoapObject(soapAction, null);

		// Log.d("getCategories", resultObject.toString());
		List<Category> list = new ArrayList<Category>();

		for (int i = 0; i < resultObject.getPropertyCount(); i++) {
			SoapObject result = (SoapObject) resultObject.getProperty(i);
			Category category = new Category();
			category.setId(Integer.parseInt(result.getPropertyAsString(0)));
			category.setName(result.getPropertyAsString(1));
			list.add(category);
		}

		return list;
	}

	/**
	 * 根据分类分页查找所拥有的商店。
	 * 
	 * @param id
	 * @param firstResult
	 * @param maxResults
	 * @return
	 * @throws Exception
	 */
	public static List<Store> getStoreListById(int id, int firstResult, int maxResults) throws Exception {
		String soapAction = "getStoreListById";
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", id + ""));
		params.add(new BasicNameValuePair("firstResult", firstResult + ""));
		params.add(new BasicNameValuePair("maxResults", maxResults + ""));
		SoapObject result = SoapService.getSoapObject(soapAction, params);
		if (result != null) {
			// TODO lllllllcao
			Log.d("getStoreListById", result.toString());

		} else {
			Log.d("getStoreListById", "null");
		}
		return null;
	}

	/**
	 * 获取指定数量的店铺,而不是获取全部
	 * 
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            结束位置
	 * @return 开始位置的Store到指定的位置的Store的集合List
	 * @throws Exception
	 */
	public static List<Store> getStoresList(int firstResult, int maxResults) throws Exception {
		String methodAction = "getStores";
		List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
		param.add(new BasicNameValuePair("firstResult", firstResult + ""));
		param.add(new BasicNameValuePair("maxResults", maxResults + ""));
		// return getStoresByMethod(methodAction, param);
		return getStoresListByMethod(methodAction, param);
	}

	/**
	 * @param firstResult
	 * @param maxResults
	 * @param sortType
	 * @return
	 */
	public static List<Store> getStoreListBySort(int firstResult, int maxResults, int sortType) {

		return null;
	}

	public static List<Map<String, List<Store>>> getCategoryStores(List<Category> categories) throws Exception {
		List<Map<String, List<Store>>> listMaps = new ArrayList<Map<String, List<Store>>>();
		for (int i = 0; i < categories.size(); i++) {
			List<Store> list = StoreService.getStoresById(categories.get(i).getId());
			if (list == null) {
				LogUtil.d("getCategoryStores", "list == null ");
				continue;
			}
			Map<String, List<Store>> map = new HashMap<String, List<Store>>();
			map.put(categories.get(i).getId() + "", list);
			listMaps.add(map);
		}
		return listMaps;
	}

}
